﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;

namespace _1042009_1042034
{
    public partial class uctCapNhatDanhMucPhong : UserControl
    {
        public uctCapNhatDanhMucPhong()
        {
            InitializeComponent();
        }
        
        int iColStt, iColMaPhong, iColTenPhong, iColMaLoaiPhong, iColDonGia, iColMaTinhTrang, iColGhiChu, iColCheck;
        protected void CreateColumn()
        {
            this.dgv.Columns.Clear();

            //lay data
            List<LoaiPhongDTO> ListLoaiPhong = Business.LoaiPhongService.LayDanhSach();
            List<TinhTrangDTO> ListTinhTrang = Business.TinhTrangService.LayDanhSach();
            DataTable DataLoaiPhong = Business.LoaiPhongService.ConvertListLoaiPhongDTOToDataTable(ListLoaiPhong);
            DataTable DataTinhTrang = Business.TinhTrangService.ConvertListTinhTrangDTOToDataTable(ListTinhTrang);

            this.dgv.AddTextColumn(true, "STT", "STT");
            this.dgv.AddTextColumn(true,"MaPhong", "Mã Phòng");
            this.dgv.AddTextColumn(false, "TenPhong", "Tên Phòng");
            this.dgv.AddComboBoxColumns(false, "MaLoaiPhong", "Loại Phòng", DataLoaiPhong, LoaiPhongDTO.ValueMember, LoaiPhongDTO.DisplayMember);
            this.dgv.AddComboBoxColumns(true, "DonGia", "Đơn Giá", DataLoaiPhong, LoaiPhongDTO.ValueMember, "DonGia");
            this.dgv.AddTextColumn(false, "GhiChu", "Ghi Chú");
            this.dgv.AddComboBoxColumns(false, "MaTinhTrang", "Tình Trạng", DataTinhTrang, TinhTrangDTO.ValueMember, TinhTrangDTO.DisplayMember);
            this.dgv.AddCheckBoxColumn("Check", "Check");

            iColStt = this.dgv.GetColumIndexByName("STT");
            iColMaPhong = this.dgv.GetColumIndexByName("MaPhong");
            iColTenPhong = this.dgv.GetColumIndexByName("TenPhong");
            iColMaLoaiPhong = this.dgv.GetColumIndexByName("MaLoaiPhong");
            iColMaTinhTrang = this.dgv.GetColumIndexByName("MaTinhTrang");
            iColGhiChu = this.dgv.GetColumIndexByName("GhiChu");
            iColCheck = this.dgv.GetColumIndexByName("Check");
            iColDonGia = this.dgv.GetColumIndexByName("DonGia");
        }            
        protected void LoadRows(int iRow)
        {

            this.dgv.Rows[iRow].ReadOnly = false;
             //coi no dang o trang may
            int Start = (this.dgv.iPage - 1) * this.dgv.iRecord + iRow;
            int Stt = Start + 1;
            string[] lst = new string[] 
                            {
                                Stt.ToString(),
                                this.dgv.MyDataTable.Rows[iRow]["MaPhong"].ToString(),                
                                this.dgv.MyDataTable.Rows[iRow]["TenPhong"].ToString(),
                                this.dgv.MyDataTable.Rows[iRow]["MaloaiPhong"].ToString(),/////2 cot dung chung 1 Datasource
                                this.dgv.MyDataTable.Rows[iRow]["MaloaiPhong"].ToString(),/////
                                this.dgv.MyDataTable.Rows[iRow]["GhiChu"].ToString(),
                                this.dgv.MyDataTable.Rows[iRow]["MaTinhTrang"].ToString(),
                                "Unchecked"
                            };
            this.dgv.Rows[iRow].SetValues(lst);
            this.dgv.SetRowColor(iRow,MyColor.Default,true);
        }
        void SetUpForm()
        {
            this.AutoSize = false;
            this.AutoScroll = false;
            this.Size = Form1.SizeContext;
        }
        protected void SetUpDataGridView()
        {
            this.dgv.iRecord = 7;
            this.dgv.BackgroundColor = MyColor.White;
            this.dgv.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            this.dgv.ScrollBars = ScrollBars.Horizontal;
            this.dgv.TopLeftHeaderCell.Value = "Select All";
            this.dgv.AutoSize = false;

           //khong cho hien dong trang.
            this.dgv.AllowUserToAddRows = false;
            this.dgv.AllowUserToDeleteRows = false;
        }

        protected void ReLoad()
        {
            //phan trang lai
            this.iTongSoBoDuLieu = Business.PhongService.Count();
            this.uctPhanTrang1.SetValue(iTongSoBoDuLieu, this.dgv.iRecord,this.dgv.iPage);
            this.dgv.iPage = this.uctPhanTrang1.GetPageIndex();

            int Start = this.dgv.iRecord * (this.dgv.iPage - 1);
            ListPhong = Business.PhongService.LayDanhSach(Start + 1, this.dgv.iRecord);

            DataTable DataPhong = Business.PhongService.ConvertListPhongDTOToDataTable(ListPhong);
            this.dgv.MyDataTable = DataPhong;

            //cap nhat lai trang.
            uctPhanTrang1.Refresh();
            this.dgv.AddRows();
            if (this.dgv.MyDataTable != null)
            {
                for (int iRow = 0; iRow < this.dgv.iRecord; iRow++)
                {
                    if (iRow < this.dgv.MyDataTable.Rows.Count)
                    {
                        this.LoadRows(iRow);
                    }
                }
            }

            //xoa nhung du lieu da bi xoa di
            for (int i = this.ListPhong.Count - 1; i >= 0; i--)
            {
                int index = Business.PhongService.KiemTraMaPhongTrongListPhong(this.ListPhong[i].MaPhong, this.ListRowsRemove);
                if (index >= 0)
                {
                    this.RemoveRow(i);
                }
            }
        }

        int iTongSoBoDuLieu = 0;


        List<PhongDTO> ListPhong;

        private void UctDanhMucPhong_Load(object sender, EventArgs e)
        {
            ////////////////
            this.SetUpDataGridView();
            this.CreateColumn();
            this.ReLoad();
            this.SetUpForm();
            //su kien
            this.dgv.CellValueChanged += new DataGridViewCellEventHandler(dgv_CellValueChanged);            
            this.uctPhanTrang1.OnPageClick += new uctPhanTrang.PageClick(uctPhanTrang1_OnPageClick);
        }      

        void uctPhanTrang1_OnPageClick(int Page)
        {
            this.dgv.iPage = Page;
            this.ReLoad();
        }


        void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int ColIndex = e.ColumnIndex;
            int RowIndex = e.RowIndex;

            if (ColIndex == this.iColMaLoaiPhong)
            {
                this.dgv.Rows[RowIndex].Cells[this.iColDonGia].Value = this.dgv.Rows[RowIndex].Cells[ColIndex].Value;
            }
            if (ColIndex != this.iColStt && this.dgv.Rows[RowIndex].Cells[this.iColCheck].Style.BackColor != MyColor.Delete)
            {
                this.dgv.SetRowColor(RowIndex, MyColor.Change,true);
            }
            
            if (ColIndex != this.iColCheck && ColIndex != this.iColStt)
            {
                this.dgv.Rows[RowIndex].Cells[this.iColCheck].Value = "Checked";
            }
        }
        
        PhongDTO GetDataOfRows(int iRow)
        {
            PhongDTO p = new PhongDTO();

            p.MaPhong = int.Parse(this.dgv.Rows[iRow].Cells[iColMaPhong].Value.ToString());
            p.MaLoaiPhong = int.Parse(this.dgv.Rows[iRow].Cells[iColMaLoaiPhong].Value.ToString());
            p.MaTinhTrang = int.Parse(this.dgv.Rows[iRow].Cells[iColMaTinhTrang].Value.ToString());
             
            p.TenPhong = "";
            if( this.dgv.Rows[iRow].Cells[iColTenPhong].Value != null)
            {
                p.TenPhong = (this.dgv.Rows[iRow].Cells[iColTenPhong].Value.ToString());
            }
            p.GhiChu = "";   
            if( this.dgv.Rows[iRow].Cells[iColGhiChu].Value != null)
            {
                p.GhiChu = (this.dgv.Rows[iRow].Cells[iColGhiChu].Value.ToString());
            }

            return p;
        }
        
        List<PhongDTO> ListRowsRemove = new List<PhongDTO>();
        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            int CheckColIndex = this.iColCheck;
            PhongDTO objPhong = new PhongDTO();
            for (int i = 0; i < this.dgv.Rows.Count; i++)
            {
                if (this.dgv.Rows[i].Cells[CheckColIndex].Value != null)
                {
                    DataGridViewCheckBoxCell CheckCell = (DataGridViewCheckBoxCell)this.dgv.Rows[i].Cells[CheckColIndex];
                    if (CheckCell.Value.ToString() == "Checked" && CheckCell.Style.BackColor != MyColor.Delete)
                    {
                        try
                        {
                            objPhong = this.GetDataOfRows(i);
                        }
                        catch
                        {
                            this.dgv.SelectedColumns[this.iColCheck].Selected = true;
                            this.dgv.Rows[i].Cells[this.iColCheck].Value = "Unchecked";
                            continue;
                        }
                        if (objPhong.KiemTra() == false)
                        {
                            this.dgv.SetRowColor(i, MyColor.Eror);
                        }
                        else
                        {
                            Business.PhongService.CapNhat(objPhong);
                            //cập nhật lại datasource, chua cap nhat lai DataBase
                            this.dgv.Rows[i].Cells[this.iColCheck].Selected = true;
                            this.dgv.Rows[i].Cells[this.iColCheck].Value = "Unchecked";
                            int iRecord = i + (this.dgv.iPage - 1)*this.dgv.iRecord;
                            //to mau cho dong do
                            this.dgv.SetRowColor(i, MyColor.Edit, true);

                        }
                    }
                }
            }
        }

        void SetStt()
        {
            int Stt = (this.dgv.iPage - 1) * this.dgv.iRecord + 1;
            for (int i = 0; i < this.dgv.Rows.Count; i++)
            {
                this.dgv[this.iColStt, i].Value = Stt.ToString();
                Stt++;
            }
        }
        void RemoveRow(int iRow)
        {
            this.dgv.Rows.RemoveAt(iRow);
            this.SetStt();
        }
        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc chắn xóa dữ liệu", "Câu hỏi dành cho bạn", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
                != DialogResult.Yes)
            {
                return;
            }
            int CheckColIndex = this.iColCheck;
            int Dem = 0;
            for (int i = this.dgv.Rows.Count - 1; i >= 0; i--)
            {
                if (this.dgv.Rows[i].Cells[CheckColIndex].Value != null)
                {
                    if (this.dgv.Rows[i].Cells[CheckColIndex].Value.ToString() == "Checked")
                    {
                        //luu vao ListXoa
                        PhongDTO PhongXoa = this.GetDataOfRows(i);
                        if (Business.PhongService.KiemTraMaPhongTrongListPhong(PhongXoa.MaPhong, this.ListRowsRemove) == -1)
                        {
                            this.ListRowsRemove.Add(PhongXoa);
                        }
                        Dem++;
                        //tien hanh xoa du lieu tren form
                        this.RemoveRow(i);
                    }
                }
            }
            if (Dem > 0)
            {
                //this.ReLoad();
            }
        }        
        private void btnCapNhatCSDL_Click(object sender, EventArgs e)
        {
            //Xoa
            if (MessageBox.Show("Dữ liệu sau khi xóa sẽ không thể phục hồi, tiếp tục?", "DataBase", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                       == DialogResult.No)
            {
                return;
            }
            for (int k = this.ListRowsRemove.Count - 1; k >= 0 ; k -- )
            {
                bool bXoaPhong = Business.PhongService.Xoa(this.ListRowsRemove[k].MaPhong);
                if ( bXoaPhong== false)
                {
                    if (MessageBox.Show("Phòng có Mã " + this.ListRowsRemove[k].MaPhong + " đang bị tham chiếu, Bạn có muốn xóa hết dữ liệu liên quan không?", "DataBase", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                        == DialogResult.Yes)
                    {
                        if( Business.PhongService.Xoa(this.ListRowsRemove[k].MaPhong, true) == true)
                            this.ListRowsRemove.RemoveAt(k);
                    }
                }
                else
                {
                    this.ListRowsRemove.RemoveAt(k);
                }
            }
            this.ReLoad();
        }

        private void btnPhucHoiCSDL_Click(object sender, EventArgs e)
        {
            DataTable dt = Business.PhongService.ConvertListPhongDTOToDataTable(this.ListRowsRemove);
            PhucHoiDuLieu frm = new PhucHoiDuLieu(dt);
            frm.OnLayDanhSachMaPhucHoi += new PhucHoiDuLieu.LayDanhSachMaPhucHoi(frm_OnLayDanhSachMaPhucHoi);
            frm.ShowDialog();
        }

        void frm_OnLayDanhSachMaPhucHoi(List<int> lstMa)
        {
            for (int i = this.ListRowsRemove.Count - 1; i >= 0; i--)
            {
                int Ma = ListRowsRemove[i].MaPhong;
                if (TimPhanTuTrongList(Ma, lstMa) > -1)
                {
                    this.ListRowsRemove.RemoveAt(i);
                }
            }
            this.ReLoad();
        }

        int TimPhanTuTrongList(int Value, List<int> lst)
        {
            for (int i = 0; i < lst.Count; i++)
            {
                if (lst[i] == Value)
                    return i;
            }
            return -1;
        }       

        private void dgv_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int iRow = this.dgv.SelectedCells[0].RowIndex;
                Color x = dgv[this.iColCheck, iRow].Style.BackColor;
                dgv.SetRowColor(iRow, x, true);
            }
            catch { }
        }
        private void dgv_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int iRow = this.dgv.SelectedCells[0].RowIndex;
                Color x = dgv[this.iColCheck, iRow].Style.BackColor;
                dgv.SetRowColor(iRow, x);
            }
            catch { }
        }

        private void dgv_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                int iRow = e.RowIndex;
                DataGridViewCheckBoxCell checkcell = (DataGridViewCheckBoxCell)this.dgv[this.iColCheck, iRow];
                if (checkcell.Value.ToString() == "Checked")
                {
                    checkcell.Value = "Unchecked";
                }
                else
                {
                    checkcell.Value = "Checked";
                }
            }
            catch { }
        }

        string Check = "Checked";
        string UnCheck = "Unchecked";
        private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == this.iColCheck)
            {
                for (int i = 0; i < this.dgv.Rows.Count; i++)
                {
                    if (dgv[iColCheck, i].Value.ToString() != Check)
                    {
                        dgv[iColCheck, i].Value = Check;
                    }
                }
            }
            string c = Check;
            Check = UnCheck;
            UnCheck = c;
        }          
    }
}
